package com.huang.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.huang.enums.UserCodeEnum;
import com.huang.resp.CommonResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * 自定义登录成功处理
 *
 * @author han
 * @since 2022-01-16 15:02:24
 */
@Log4j2
@Component
public class DefaultAuthenticationSuccessHandler implements ServerAuthenticationSuccessHandler {

    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        log.info("登录成功时！");
        return Mono.defer(()-> Mono.just(webFilterExchange.getExchange().getResponse())
                .flatMap(response -> {
                    DataBufferFactory dataBufferFactory = response.bufferFactory();
                    byte[] bytes = JSONObject.toJSONString(CommonResult.success(UserCodeEnum.LOGIN_PASSWORD_SUCCESS)).getBytes();
                    DataBuffer dataBuffer = dataBufferFactory.wrap(bytes);
                    return response.writeWith(Mono.just(dataBuffer));
                })

        );
    }


}
